package vn.com.demand.lux.editor;

import java.util.Date;
import java.util.Locale;

import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.nebula.widgets.datechooser.DateChooserCombo;
import org.eclipse.nebula.widgets.formattedtext.DateFormatter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.TraverseEvent;
import org.eclipse.swt.events.TraverseListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;

import vn.com.demand.lux.Activator;

public class DateCellEditor extends CellEditor {

	DateChooserCombo dateCombo;

	private static final int defaultStyle = SWT.NONE;
	
	public DateCellEditor(Composite parent) {
		this(parent, defaultStyle);
	}
	
	public DateCellEditor(Composite parent, int style) {
		this(parent, style, new Locale("vi", "VN"));
	}
	
	public DateCellEditor(Composite parent, int style, Locale locale) {
		super(parent, style);
	}

	@Override
	protected Control createControl(Composite parent) {
		dateCombo = new DateChooserCombo(parent, getStyle());
		dateCombo.setFormatter(new DateFormatter(Activator.getDefault().getDateFormatTypePreferences()));
		dateCombo.setFont(parent.getFont());
		dateCombo.addSelectionListener(new SelectionAdapter() {
			public void widgetDefaultSelected(SelectionEvent event) {
				System.out.println("Applying....");
				applyEditorValueAndDeactivate();
			}

		});

		dateCombo.addTraverseListener(new TraverseListener() {
			public void keyTraversed(TraverseEvent e) {
				if (e.detail == SWT.TRAVERSE_ESCAPE
						|| e.detail == SWT.TRAVERSE_RETURN) {
					e.doit = false;
				}
			}
		});

		dateCombo.addFocusListener(new FocusAdapter() {
			public void focusLost(FocusEvent e) {
				DateCellEditor.this.focusLost();
			}
		});
		dateCombo.setValue(null);
		return dateCombo;
	}

	protected void applyEditorValueAndDeactivate() {
		// must set the selection before getting value
		Object newValue = doGetValue();
		markDirty();
		boolean isValid = isCorrect(newValue);
		setValueValid(isValid);
		if (!isValid) {
			System.out.println("INVASLID -------------------------------------");
		}
		fireApplyEditorValue();
		deactivate();
	}

	protected Object doGetValue() {
		return dateCombo.getValue();
	}

	@Override
	protected void doSetFocus() {
		dateCombo.setFocus();
	}

	@Override
	protected void doSetValue(Object value) {
		dateCombo.setValue((Date) value);
	}
}
